﻿using System;
using System.Collections.Generic;
using System.Web;

namespace WebMonitor {
    public class MonitorHandlerFactory : IHttpHandlerFactory {
        private static readonly List<Type> httpHandlers;

        static MonitorHandlerFactory() {
            var allTypes = new List<Type>(typeof (MonitorHandlerFactory).Assembly.GetTypes());
            httpHandlers = allTypes.FindAll(t => typeof(IHttpHandler).IsAssignableFrom(t));
        }

        public IHttpHandler GetHandler(HttpContext context, string requestType, string url, string pathTranslated) {
            var u = LastSegment(context.Request.Url).Split('.')[0];
            var thisController = httpHandlers.Find(t => t.Name.StartsWith(u, StringComparison.InvariantCultureIgnoreCase));
            return (IHttpHandler)Activator.CreateInstance(thisController);
        }

        public string LastSegment(Uri u) {
            return u.Segments[u.Segments.Length - 1];
        }

        public void ReleaseHandler(IHttpHandler handler) {}
    }
}